package com.maktoub.apiclientstart;

import com.maktoub.apiclientstart.client.ApiInterfaceClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
@ConfigurationProperties("api.client")
@ComponentScan
@Data
public class ApiClientConfig {

    private String accessKey;
    private String secrectKey;
    private int redisPort=6379;
    private String redisPassword="root";
    private int redisDatabase=0;
    @Bean
    public ApiInterfaceClient apiInterfaceClient(){
        return new ApiInterfaceClient(accessKey,secrectKey);
    }


    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setPassword(redisPassword);
        config.setPort(redisPort);
        if (redisPassword != null && !redisPassword.isEmpty()) {
            config.setPassword(redisPassword);
        }
        config.setDatabase(redisDatabase);
        return new LettuceConnectionFactory(config);
    }
    @Bean(name = "redisTemplate2")
    public RedisTemplate<String, Object> redisTemplate2(RedisConnectionFactory redisConnectionFactory) {
        //创建Template，键是字符串类型的情况下，存储任意类型的对象到 Redis 中
        RedisTemplate<String, Object> stringObjectRedisTemplate = new RedisTemplate<>();
        stringObjectRedisTemplate.setConnectionFactory(redisConnectionFactory);

        stringObjectRedisTemplate.setKeySerializer(RedisSerializer.string());
        stringObjectRedisTemplate.setHashKeySerializer(RedisSerializer.string());

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        stringObjectRedisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        stringObjectRedisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        return stringObjectRedisTemplate;
    }

}
